<?php
/**
 * Created by PhpStorm.
 * User: tom_xia
 * Date: 2018/8/13
 * Time: 18:50
 * 小程序二维码
 */
require "login_filter.php";

use app\cls\tom\JsSDK;
use app\cls\tom\Response;
use app\cls\tom\SysResource;
use app\cls\tom\Tools;

$dataStr = file_get_contents("php://input");

if (empty($dataStr)) {
    echo 1;
    Response::badRequest();
}
$data = @json_decode($dataStr, true);
if (empty($data)) {
    echo 2;
    Response::badRequest();
}
if (empty($data["material_id"])) {
    echo 3;
    Response::badRequest();
}
$fileNameKey = md5($dataStr);
$urlKey = REDIS_PREFIX . "material_poster_{$fileNameKey}";
$redis = SysResource::getRedis();
$url = $redis->get($urlKey);
if ($url) {
    Response::output(0, "ok", ["file_path" => $url]);
} else {
    $savePath = CDN_PATH . "/poster_qrcode/";
    $saveFile = $savePath . $fileNameKey . ".png";
    if (!file_exists($savePath)) {
        $isCreateSuccess = mkdir($savePath, 0777, true);
        if (!$isCreateSuccess) {
            Response::output(-1, "服务器内部异常-内部权限不足");
        }
    }
    if (file_exists($saveFile) && filesize($saveFile) > 0) {
        $url = str_replace(CDN_PATH, CDN_HOST, $saveFile);
    } else {

        $materialId = $data["material_id"];
        unset($data["material_id"]);
        unset($data["false"]);
        unset($data["auto_color"]);
        $newDataStr = json_encode($data);
        $url = "";

        $appKey = WX_PUBLIC_APP_ID;
        $appSecret = WX_PUBLIC_APP_SECRECT;

        $jssdk = new JsSDK($appKey, $appSecret);
        try {
            $accessToken = $jssdk->getAccessToken();
            $data = http_build_query($data);
            $re = Tools::curl("https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}", $newDataStr, "post", false, ["Content-Type:application/json"]);
            $res = @json_decode($re, true);
            if ($res && isset($res["errcode"])) {
                $re123 = $res["errcode"] . "--" . $_SERVER['SERVER_ADDR'];
                if($res["errcode"]==40001){
                    $accessToken = $jssdk->getAccessTokenRefresh();
                    $re = Tools::curl("https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}", $newDataStr, "post", false, ["Content-Type:application/json"]);
                }else{
                    Response::output(-1, "请求失败 msg==>{$re}{$re123}:{$res["errmsg"]}");
                }
            }
            file_put_contents($saveFile, $re);
            if (file_exists($saveFile) && filesize($saveFile) > 0) {
                $url = str_replace(CDN_PATH, CDN_HOST, $saveFile);
            } else {
                Response::output(-1, "服务器内部异常-写存储异常");
            }
        } catch (\Exception $e) {
            //            Response::output(-1,"请求失败 msg==>".$e->getMessage());
            Response::output(-1, "请求失败 msg==>" . $_SERVER['SERVER_ADDR'] . $e->getMessage());
        }
    }
    $redis->setex($urlKey, 10 * 60, $url);
    Response::output(0, "ok", ["file_path" => $url]);
}